package org.example.resourceplatform.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "subject",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "subject_name", name = "uk_subject_name")
        })
@Getter
@Setter
@NoArgsConstructor
public class Subject {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "subject_id")
    private Integer subjectId;

    @NotBlank(message = "科目名称不能为空")
    @Size(max = 50, message = "科目名称长度不能超过50个字符")
    @Column(name = "subject_name", nullable = false, unique = true, length = 50)
    private String subjectName;

    @CreationTimestamp
    @Column(name = "create_time", nullable = false, updatable = false)
    private LocalDateTime createTime;

    @OneToMany(mappedBy = "subject", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Document> documents = new ArrayList<>();

    public Subject(String subjectName) {
        this.subjectName = subjectName;
    }

    public void addDocument(Document document) {
        if (documents == null) {
            documents = new ArrayList<>();
        }
        documents.add(document);
        document.setSubject(this);
    }

    public void removeDocument(Document document) {
        if (documents != null) {
            documents.remove(document);
            document.setSubject(null);
        }
    }

    @Override
    public String toString() {
        return "Subject{" +
                "subjectId=" + subjectId +
                ", subjectName='" + subjectName + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}